package com.jy.api.controller.admin;

import com.jy.api.domain.Material;
import com.jy.api.service.MaterialService;
import com.jy.api.signUpReq.admin.MaterialSignUpReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Created by lihu on 2017/11/11.
 */

@Slf4j
@RestController
@RequestMapping(value = "v1/admin", produces = "application/json;charset=utf-8")
public class MaterialController {

    @Autowired
    MaterialService materialService;

    /**
     * 查询店铺所有原材料
     *
     * @param storeId
     * @param pageable
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/material/search")
    public ResponseEntity getMaterialList(@RequestParam(name = "storeId") String storeId,
                                          @RequestParam(name = "code") String code,
                                          @PageableDefault(value = 10) Pageable pageable) {
        return new ResponseEntity(materialService.searchCode(storeId, code, pageable), HttpStatus.OK);
    }

    /**
     * 查询店铺所有原材料
     *
     * @param storeId
     * @param pageable
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/material")
    public ResponseEntity getMaterialList(@RequestParam(name = "storeId") String storeId,
                                          @PageableDefault(value = 10) Pageable pageable) {
        Page<Material> materials = materialService.getMaterial(storeId, pageable);
        return new ResponseEntity(materials, HttpStatus.OK);
    }


    /**
     * 原材料上传(新增,修改)
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/material")
    public ResponseEntity putMaterial(@Valid @RequestBody MaterialSignUpReq materialSignUpReq,
                                      BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, materialSignUpReq={}", materialSignUpReq);
            return new ResponseEntity(bindingResult.getFieldError().getDefaultMessage(), HttpStatus.BAD_REQUEST);
        }
        materialService.addMaterial(materialSignUpReq);
        return new ResponseEntity(HttpStatus.OK);
    }


}
